package com.itrip.itripauth.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itrip.common.vo.UserVo;
import com.itrip.itripauth.entity.Image;
import com.itrip.itripauth.service.CommentService;
import com.itrip.itripauth.service.ImageService;
import com.itrip.itripauth.util.*;
import com.itrip.itripauth.vo.CommentCountVo;
import com.itrip.itripauth.vo.CommentListVo;
import com.itrip.itripauth.vo.CommentVo;
import com.itrip.itripauth.vo.HotelScoreVo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author 四阶段项目二组
 * @since 2020-02-25
 */
@RestController
@RequestMapping("/biz/api/comment")
@CrossOrigin
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private ImageService imageService;
    @Resource
    private RedisUtil redisUtil;

    @GetMapping("gethoteldesc/{hotelId}")
    public Dto getHotelDesc(
            @PathVariable Integer hotelId
            ,HttpServletRequest request
    ){
        try {
            return DtoUtil.returnDataSuccess(commentService.getHotelDesc(hotelId));
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取酒店信息失败");
        }
    }

    @GetMapping("/gettraveltype")
    public Dto getTravelType(HttpServletRequest request) {
        try {
            return DtoUtil.returnDataSuccess(commentService.getTravelType());
        }catch (Exception e){
            return DtoUtil.returnFail("获取陆游类型列表失败");
        }
    }

    @PostMapping(value = "/upload", produces = "application/json")
    public Dto upLoad(@ApiParam(name = "file", value = "图片路径", required = true) @RequestParam MultipartFile file) {
        List<String> list = new ArrayList<>();
        String name = file.getOriginalFilename();
        String filePath = "/Library/idea/LoveToTravel/image";
        if (file.isEmpty()) {
            return DtoUtil.returnFail("文件为空");
        }
        try {
            uploadFile(file.getBytes(), filePath, name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        list.add(name);
        return DtoUtil.returnSuccess("图片上传成功!", list);
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + "/" + fileName);
        out.write(file);
        out.flush();
        out.close();
    }


    @PostMapping(value = "/add", produces = "application/json")
    public Dto addComment(@RequestBody CommentVo commentVo,HttpServletRequest request) {
        try {
            //获取当前时间和用户ID
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            Date date = new Date();
            String newDate = simpleDateFormat.format(date);
            //验证token是否过期
            String token = request.getHeader("token");
            System.out.println(token);
//验证token
            UserVo userVo=null;
            try {
                Claims claims = JwtUtil.checkToken(token);
                System.out.println(claims);
                claims.remove(claims.getSubject());
                userVo= (UserVo) redisUtil.get(token);
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("token失效，请重登录", "100000");
            }
            if (userVo==null){
                return DtoUtil.returnFail("token失效，请重登录", "100000");
            }
            commentVo.setUserId(userVo.getId());
            Date date2 = simpleDateFormat.parse(newDate);
            commentVo.setCreationDate(date2);
            int i = commentService.addComment(commentVo);
            if (i>0) {
                return DtoUtil.returnSuccess("评论成功");
            }else {
                return DtoUtil.returnFail("评论失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("评论失败");
        }
    }

    @PostMapping("/delpic")
    public Dto delPic(@RequestParam Object imgName){
        try {
            String filePath ="/Library/idea/LoveToTravel/image/"+imgName;
            File file=new File(filePath);
            if (file.exists() && file.isFile()){
                if (file.delete()) {
                    return DtoUtil.returnSuccess("删除成功");
                }
            }
            return DtoUtil.returnFail("删除失败");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("删除失败");
        }
    }

    @ApiOperation("查询酒店评论")
    @GetMapping("gethotelscore/{hotelId}")
    public Dto queryhotelpolicy(
            @ApiParam(name = "hotelId",required = true)
            @PathVariable String hotelId){
        HotelScoreVo hotelScoreVo = commentService.scoreList(Integer.valueOf(hotelId));
        return  DtoUtil.returnDataSuccess(hotelScoreVo);
    }
    @ApiOperation("查询酒店评论数量")
    @GetMapping("getcount/{hotelId}")
    public Dto getcount(
            @ApiParam(name = "hotelId",required = true)
            @PathVariable String hotelId){
        CommentCountVo commentCountVo = commentService.commCount(Integer.valueOf(hotelId));
        return  DtoUtil.returnDataSuccess(commentCountVo);
    }

    @ApiOperation("根据满意度，图片进行分页查询")
    @PostMapping("/getcommentlist")
    public Dto getCommentList(
            @ApiParam(name = "vo",required = true)
            @RequestBody CommentListVo vo){
        return DtoUtil.returnDataSuccess(commentService.getCommentList(vo));
    }

    @ApiOperation("根据target_id查询评论图片")
    @GetMapping("getimg/{targetId}")
    public Dto getimg(
            @ApiParam(name = "targetId",required = true)
            @PathVariable Integer targetId
    ){
        QueryWrapper<Image> queryWrapper=new QueryWrapper<Image>();
        queryWrapper.eq("type",2);
        queryWrapper.eq("target_id",targetId);
        return  DtoUtil.returnDataSuccess(imageService.list(queryWrapper));
    }
}
